import api, { APIResponse } from './api'
import { Connection, CreateConnectionData, UpdateConnectionData, ConnectionTestResult, DatabaseSchema } from '@/types/connection'

// 获取连接列表
export const getConnections = (): Promise<APIResponse<{
  connections: Connection[]
  total: number
}>> => {
  return api.get('/connections').then(res => res.data)
}

// 获取单个连接
export const getConnection = (id: string): Promise<APIResponse<Connection>> => {
  return api.get(`/connections/${id}`).then(res => res.data)
}

// 创建连接
export const createConnection = (data: CreateConnectionData): Promise<APIResponse<Connection>> => {
  return api.post('/connections', data).then(res => res.data)
}

// 更新连接
export const updateConnection = (id: string, data: UpdateConnectionData): Promise<APIResponse<Connection>> => {
  return api.put(`/connections/${id}`, data).then(res => res.data)
}

// 删除连接
export const deleteConnection = (id: string): Promise<APIResponse<void>> => {
  return api.delete(`/connections/${id}`).then(res => res.data)
}

// 测试连接
export const testConnection = (id: string): Promise<APIResponse<ConnectionTestResult>> => {
  return api.post(`/connections/${id}/test`).then(res => res.data)
}

// 获取数据库列表
export const getDatabases = (id: string): Promise<APIResponse<string[]>> => {
  return api.get(`/connections/${id}/databases`).then(res => res.data)
}

// 获取表列表
export const getTables = (id: string, database: string): Promise<APIResponse<string[]>> => {
  return api.get(`/connections/${id}/tables`, {
    params: { database }
  }).then(res => res.data)
}

// 获取表结构
export const getTableSchema = (id: string, database: string, table: string): Promise<APIResponse<{
  columns: Array<{
    name: string
    type: string
    nullable: boolean
    default?: string
    comment?: string
  }>
}>> => {
  return api.get(`/connections/${id}/schema`, {
    params: { database, table }
  }).then(res => res.data)
}

// 获取完整数据库schema
export const getDatabaseSchema = (id: string, database: string): Promise<APIResponse<DatabaseSchema>> => {
  return api.get(`/connections/${id}/schema/full`, {
    params: { database }
  }).then(res => res.data)
}

// 获取连接统计
export const getConnectionStats = (id: string): Promise<APIResponse<{
  total_executions: number
  success_rate: number
  avg_response_time: number
  last_used_at?: string
  most_used_databases: Array<{
    database: string
    count: number
  }>
}>> => {
  return api.get(`/connections/${id}/stats`).then(res => res.data)
}